const url: string = 'https://api.thecatapi.com/v1/images/search'
const button: HTMLButtonElement | null = document.querySelector('.button')
const tableBody: HTMLTableElement | null = document.querySelector('#table-body')

interface CatType {
  id: string;
  url: string;
  width: number;
  height: number;
}

class Webdisplay {
  public static addData(data: CatType): void {
    const cat: Cat = new Cat(data.id, data.url, data.height, data.width)
    console.log({ cat })
    const tableRow: HTMLTableRowElement = document.createElement('tr')
    tableRow.innerHTML = `
      <tr>
        <td>${cat.id}</td>
        <td><img src="${cat.url}" /></td>
        <td>${cat.height.toString()}</td>
        <td>${cat.width.toString()}</td>
        <td>${cat.url}</td>
        <td><a href="#">X</a></td>
      </tr>

`
    tableBody?.append(tableRow)
  }
  public static deleteData(deleteButton: HTMLAnchorElement): void {
    const td = deleteButton.parentElement as HTMLTableCellElement
    const tr = td?.parentElement as HTMLTableRowElement
    tr.remove()
  }
}

class Cat implements CatType {
  id: string;
  url: string;
  width: number;
  height: number;

  constructor(id: string, url: string, width: number, height: number) {
    this.id = id
    this.url = url
    this.width = width
    this.height = height
  }
}

async function getJSON<T>(url: string): Promise<T> {
  const response: Response = await fetch(url)
  const json: Promise<T> = await response.json()
  return json
}
console.log(getJSON(url))

async function getData(): Promise<void> {
  console.log(11)
  try {
    const json: CatType[] = await getJSON<CatType[]>(url)
    const data: CatType = json[0]
    console.log(data)
    Webdisplay.addData(data)

  } catch (err: Error | unknown) {
    let message: string
    if (err instanceof Error) {
      message = err.message
    } else {
      message = String(err)
    }
    console.log(err)
  }
}

button?.addEventListener<'click'>('click', getData)
tableBody?.addEventListener<'click'>('click', (ev: MouseEvent) => {
  Webdisplay.deleteData(ev?.target)
})
